<?
class SearchSphinxForm extends Form
{
	private $search_catid = 0,$search_top_catid = 0,$search_sec_catid = 0;

	function SearchSphinxForm()
	{
		Form::Form('SearchResultForm');

		$this->link_css('style/listItem.css');
		
		$keywords  		= AZLib::getParam('keywords');
		
		if($keywords != '')
		{
			CGlobal::$website_title = "$keywords - Tìm bởi ".WEB_NAME;
			CGlobal::$meta_desc = "Tìm kiếm nội dung liên quan tới $keywords - Tìm bởi ".WEB_NAME;
		}
		else{
			CGlobal::$website_title = "Trang tìm kiếm sản phẩm";
			CGlobal::$meta_desc = "Trang tìm kiếm sản phẩm";
		}
		
		$this->search_catid = (int)Url::get('search_catid',-1);
		
		if($this->search_catid<=0 || !isset(CGlobal::$allCategories[$this->search_catid]) || CGlobal::$allCategories[$this->search_catid]['status'] == 'HIDE')
		{
			$this->search_catid = 0;
		}
		
		if($this->search_catid)
		{
			$curCategory = CGlobal::$allCategories[$this->search_catid];
			
			if($curCategory['parent_id'] && isset(CGlobal::$allCategories[$curCategory['parent_id']]))//Cấp 2 hoặc cấp 3
			{
				$parent_cat = CGlobal::$allCategories[$curCategory['parent_id']];
				
				$this->search_top_catid	=	$curCategory['parent_id'];
				$this->search_sec_catid	=	$this->search_catid;
			}
			else 
			{
				$this->search_top_catid	=	$this->search_catid;
			}
		}
	}
	
	function strippedLink($str)
	{
		if((strlen($str) -38 ) < 3 ){  
			return $str;
		}
		return substr( $str , 0, 18 ).'...'.substr( $str , -16 );
	}
	
	function draw()
	{	
		global $display;
		
		if($this->search_catid)
		{
			$keywords = AZLib::getParam('keywords');
			
			if($keywords !='')
			{
				global $display;
				$page_no=(int)Url::get('page_no',1);
				
				if($page_no<=0){
					$page_no = 1;
				}
		
				$item_per_page 	= 30;
				
				$sql 		='SELECT * FROM item WHERE ';
				$where 		='';				
				
				$curMainCat 	= CGlobal::$curMainCat;
				$curLevel2Cat 	= CGlobal::$curLevel2Cat;
				
				$sql		.= CGlobal::$item_condition." ORDER BY item_order ASC";
				
				$total_row = DB::count("item",CGlobal::$item_condition);
				
		        if(CGlobal::$allCategories[$this->search_catid]['parent_id'] && isset(CGlobal::$allCategories[CGlobal::$allCategories[$this->search_catid]['parent_id']]))//DM cấp 2
		        {
		            $ebname = CGlobal::$allCategories[CGlobal::$allCategories[$this->search_catid]['parent_id']]['ebname'].'-'.CGlobal::$allCategories[$this->search_catid]['ebname'];
		        }
		        else
		        {
		            $ebname 	= CGlobal::$allCategories[$this->search_catid]['ebname'];
		        }
		
		        #######################################################################################
		        #Paging
		    	
		    	$filter_get = Url::get('filter');
		    	$min 		= Url::get('min');
		    	$max 		= Url::get('max');
		    	$order 		= Url::get('order');
		    	
				$paging = AZPagging::paging_list($limit,$total_row,$item_per_page,10,'page_no','',true,'Sản phẩm','Trang');
				
				$sql	.=$limit;
				#Paging
				#######################################################################################
		        
				$items 	= array();
				
				$re 	= DB::query($sql);				
					
				if($re)
				{	
					while ($item = mysql_fetch_assoc($re))
					{									
						if(isset(CGlobal::$allCategories[$item['category_id']])){
							$item['href'] = WEB_DIR.CGlobal::$allCategories[$item['category_id']]['nice_name']."/p{$item['id']}/".AZLib::safe_title($item['name']).".html";
						}
						else{	
							$item['href'] = WEB_DIR."p{$item['id']}/".AZLib::safe_title($item['name']).".html";
						}
				
						$item['modify_time'] = date('H:i | d.m.y',$item['modify_time']);
						
						$item['price'] 		= AZLib::convertCurrency($item['price'],$item['currency_id']);
						$item['price_out'] 	= AZLib::convertCurrency($item['price_out'],$item['currency_id']);
						$item['currency_id'] = 1;
						
						$item['price_num'] = (int)$item['price'];
						
						if($item['price']){
							$item['price'] = number_format($item['price'],0,',','.');
						}
						else{
							$item['price'] = '';
						}
						
						$item['price_title'] = 'Giá bán';	
						
						if($item['price_out']>0)
						{
							$item['price_out'] = number_format($item['price_out'],0,',','.').($item['currency_id']==' '?' '.CGlobal::$currency[$item['currency_id']]:'');
						}
						else{
							$item['price_out'] = '0';
						}
						
						$item['name'] 		= AZLib::filter_title($item['name']);
						
						if ($item['img_url']){
							$item['img_thumb_wl'] 		= AZLib::getImageThumb($item['img_url'],180,0,1,$item['img_server']);
						}
						else{
							$item['img_url'] 			=  '';
						}
						
						if(!CGlobal::$curLevel2Cat){
							if(isset(CGlobal::$allCategories[$item['category_id']])){
								$item['cat_name'] = CGlobal::$allCategories[$item['category_id']]['name'];
							}
							else{
								$item['cat_name'] = "ID: {$item['category_id']}";
							}
						}
								
						$items[$item['id']] = $item;
					}
				}
				
				$display->add('page',$page_no);
				$display->add('items', $items);		
				$display->add('paging', $paging);
				
				$display->output("sphinx_search");
			}
			else
			{
				echo '<div style="padding:20px;color:#f00;font-size:18px;border:1px solid #ccc" align="center">
			        	Bạn chưa nhập vào từ khóa cần tìm kiếm!
			         </div>';
			}
		}
		else
		{
			echo '<div style="padding:20px;color:#f00;font-size:18px;border:1px solid #ccc" align="center">
		        	Bạn chưa chọn danh mục tìm kiếm!
		         </div>';
		}
	}

	
	function draw2()
	{
		$keywords  		= AZLib::getParam('keywords');
		$total_item     = 0;
		$search_result	= false;
		$items			= array();
		$paging		= '';
		$cmd			= '';
		$cat_search_id = 0;
		$item_array = array();
		$listCat    = array();
		
		if($keywords)
		{
			//AZLib::getCats();
			require( "./includes/sphinxapi.class.php" );
		
			foreach(CGlobal::$allCategories as $value){
				
				if($value['parent_id'] == 0){
					$cat_list[$value['id']] = $value['brief_name'];
				}
			}
			
			$category = $this->getTotalPerCategory($keywords);
			
			foreach($category as $row){
				$row['brief_name'] 					  =(isset($cat_list[$row['level_1_catid']])&&$cat_list[$row['level_1_catid']])? $cat_list[$row['level_1_catid']] : "Khác" ;		
				$listCat[$row['level_1_catid']] = array("level_1_catid"=>$row["level_1_catid"],"brief_name"=>$row['brief_name'],"count_ad"=>$row['@count']);
			}
			
			$total = 0;
			$catid = 0;
			$catActive = '';
			$total_cat =0;
			
			if($listCat){
				$first_val = array_slice($listCat, 0, 1);
				$total = $first_val[0]['count_ad'];
				$catid = $first_val[0]['level_1_catid'];
				$catActive = $first_val[0]['brief_name'];
				$total_cat = count($listCat);
			}
			
			
			$i=0;
			$allrecord = 0;
			$otherCat  = '';
			$cat_content = "";
			foreach($listCat as $cat){
				if($i < 3){
					$active =($i==0)?"class=\"active\"":"";
					$cat_content.= "<li id=\"tab_{$i}\" $active onclick=\"javascript:acive_tab_cat(this);\"><a href=\"javascript:void(0);\" onclick=\"javascript:search_cat({$cat['level_1_catid']},{$cat['count_ad']},1,0);\"><span id=\"kby_{$cat['level_1_catid']}\">".$cat['brief_name']." <font style=\"color: #5a7e92;font-weight: normal;\">(".$cat['count_ad'].")</font></span></a></li>";
				}
				else {
					$otherCat .= "<div class=\"other\"><a href=\"javascript:void(0);\" onclick=\"javascript:search_cat({$cat['level_1_catid']},{$cat['count_ad']},1,0);acive_tab_cat(this);\" id=\"tab_{$i}\"><span id=\"kby_{$cat['level_1_catid']}\">".$cat['brief_name']." <font style=\"color: #5a7e92;font-weight: normal;\">(".$cat['count_ad'].")</font></span></a></div>";
				}
				$i++;
				$allrecord = $allrecord + $cat['count_ad'];
			}
			
			$display->add("cat_content",$cat_content);
			$display->add("CatActiveId",$catid);
			$display->add("catActive",$catActive);
			$display->add("listCat",$listCat);
			$display->add("allrecord",$allrecord);
			$display->add("otherCat",str_replace(array(chr(13),chr(10)),"",$otherCat));
			$display->add("total_cat",$total_cat);	
			//Init for sphinx search paging						
			$pager = new Pager();
			//config
			$limit = SEARCH_LIMIT;
						
			$pager->type = "search";
			$pager->catid = $catid;
			$pager->total = $total;
			$pager->limit = $limit;
			$pager->page_param = 'page';
			$pager->page = 1;
						
			$offset = $pager->get_offset();
			$limit_from = $pager->limit_from();
			$limit_to = $pager->limit_to();															
					
			//Sphinx search by Nova
			$q 			= $keywords;
			$mode 		= SPH_MATCH_EXTENDED2;
			//Init config
			$host 		= SPHINX_SERVER;
			$port 		= SPHINX_PORT;
			//$index 		= SPHINX_INDEX;
			$index 		= "enbac delta";
			$filtervals = array();			
			$ranker 	= SPH_RANK_WORDCOUNT;
			
			$cl = new SphinxClient();
			$cl->SetServer( $host, $port );
			$cl->SetConnectTimeout( 1 );
			$cl->SetWeights( array( 100, 1 ) );
			$cl->SetMatchMode( $mode );
			
			//filter			
			if($catid){
				$cl->SetFilter( 'level_1_catid', array($catid) );
			}
			$cl->SetFilter( 'status', array('1'));
                        $cl->SetFieldWeights(array('user_name'=>10000,'name'=>1000,'description'=>1));
			//$cl->SetSortMode( SPH_SORT_EXTENDED, 'up_time DESC' );			
			//$cl->SetSortMode( SPH_SORT_RELEVANCE);//Sort theo kq chính xác nhất			
			//$cl->SetSortMode ( SPH_SORT_EXPR, "@weight + ( user_karma + ln(pageviews) )*0.1");
			$cl->SetSortMode ( SPH_SORT_EXPR, "@weight");//Sort theo trọng số
			
			//SPH_RANK_WORDCOUNT
			//SPH_MATCH_EXTENDED2


			//end filter
			$cl->SetLimits( $offset , $limit, 10000 );
			$cl->SetRankingMode( $ranker );
			$cl->SetArrayResult( true );
									
			$res = $cl->Query( $q, $index);
			/*echo '<pre>';
			print_r($res["matches"]);*/
			
			if($res && isset($res["matches"])){
				if( is_array($res["matches"]) ){
					foreach( $res["matches"] as $results ){	
						$list_item_id[] = $results['id'];	
					}							
				}
				$comma_separated = join(",", $list_item_id);
				
			}
			if($total){										
				if($limit_to > $total){
					$limit_to = $total;
				}
				
				$comma_separated = join(",", $list_item_id);
			
				if($comma_separated){
					//$sql = "SELECT id,name,up_time,price,user_id,user_name, level_1_catid,category_id,description,img_url, img_server FROM item WHERE id IN($comma_separated) AND status=1 ORDER BY up_time DESC";						
					//$sql = "SELECT id,name,up_time,price,user_id,user_name, level_1_catid,category_id,description,img_url, img_server FROM item WHERE id IN($comma_separated) AND status=1  AND state=0 ORDER BY find_in_set(id,'$comma_separated')";	
					$sql = "SELECT id,name,up_time,price,user_id,user_name, level_1_catid,category_id,description,img_url, img_server FROM item WHERE id IN($comma_separated) AND status=1 ORDER BY find_in_set(id,'$comma_separated')";	
										
					$search_result = DB::query($sql);		
				
					$pager->total = $total;
					$paging 	= $pager->page_link();
				}		
			}
		}

        $highlight='';
		if($keywords){
			$highlight=$str_search = str_replace( array('+','/','|','-','*') , "", $keywords );
			$highlight = AZLib::trimSpace($highlight);

			$highlight = str_replace( "'" , '', $highlight );
			$highlight = str_replace( "&#39;" , '', $highlight );
			$highlight = str_replace( "&quot;" , '', $highlight );
		}

                $highlight1 = '';
		if($highlight){
			$arr=explode(' ',$highlight);

			if($arr){
				$highlight="";
				foreach($arr as $word){
                                    $highlight=($highlight?$highlight.', ':'')."'$word'";
                                    $highlight1=($highlight1?$highlight1.',':'').$word;
				}
			}
		}
		if($keywords && $search_result){
			while($item=mysql_fetch_assoc($search_result)) {
			
				$item['profile_url'] = WEB_DIR.$item['user_name'];
				$item['name_hl'] = AZLib::HighLightKeyword(strip_tags(AZLib::filter_title($item['name'])),$highlight1);
				$item_time = TIME_NOW - $item['up_time'];	
				//neu nho hon 1h thi tinh ra phut
				if($item_time < 3600){
					$item['item_time'] = floor($item_time/60). " phút trước đây";					
				}
				//neu nho hon 1 ngay thi tinh ra gio`
				elseif($item_time < 86400){
					$item['item_time'] = floor($item_time/3600). " giờ trước đây";
				}	
				else{
					$item['item_time'] =  date('\n\gà\y j \t\há\n\g n',$item['up_time']);
				}	
				
				$item['description'] = AZLib::HighLightKeyword(AZLib::delDoubleSpace(AZLib::trimSpace(strip_tags( AZLib::post_db_parse_html(preg_replace('/\[[0-9]{1,3}\]/', '', $item['description']))))),$highlight1,35,"background:yellow;font-size:14px;font-weight:bold;color:blue;");
				
				$ebname = AZLib::safe_title($item['name']);
				
				$ebname_tmp = substr(AZLib::safe_title($item['name']) , 0, 20);				
				
				if(isset(CGlobal::$allCategories[$item['category_id']])){
					$item['item_url'] = WEB_DIR.AZRewrite::formatUrl('?page=item_detail&id='.$item['id'].'&ebname='.$ebname.'&nice_name='.CGlobal::$allCategories[$item['category_id']]['nice_name']);
					$item['item_url_tmp'] = WEB_ROOT.CGlobal::$allCategories[$item['category_id']]['nice_name'].'/p'.$item['id'].'/'.$ebname_tmp.'...';
				}
				else{	
					$item['item_url'] = WEB_DIR.AZRewrite::formatUrl('?page=item_detail&id='.$item['id'].'&ebname='.$ebname);
					$item['item_url_tmp'] = WEB_ROOT.'p'.$item['id'].'/'.$ebname_tmp.'...';
				}

				if($item['img_url']){
					$item['img_url'] = AZLib::getImageThumb($item['img_url'],110,0,1,$item['img_server']);
				}
				
				$item['price'] 		 = number_format($item['price'],0,',','.');
						
			 	$item_array[] = $item;						
			}
		}				

		global $start_rb;
		$mtime 			= microtime();
		$mtime 			= explode(" ",$mtime);
		$mtime 			= $mtime[1] + $mtime[0];
		$end_rb 		= $mtime;			
		$search_time = round(($end_rb - $start_rb),3);	


		$display->add('limit_from', $limit_from);
		$display->add('limit_to', $limit_to);
		$display->add('search_time', $search_time);
		
		$display->add('keywords',$keywords);
		$display->add('base_url',WEB_ROOT);
		$display->add('highlight',$highlight);
		$display->add('total_item_cat',$total);
		$display->add('name_item_cat',$catActive);
		$display->add('block_id',Module::$block_id);
		$display->add('paging', $paging);
		$display->add('items', $item_array);
		
		$display->output('sphinx_search');
	}

        

	function getTotalPerCategory($keywords){
		$q = $keywords;
		
		$mode = SPH_MATCH_EXTENDED;
		
		$item = array();
		$comma_separated = "";
		//Init config
		$host = SPHINX_SERVER;
		$port = SPHINX_PORT;
		$index = '*';										

		$ranker = SPH_RANK_PROXIMITY_BM25;			
		
		$cl = new SphinxClient();
		
		$cl->SetServer( $host, $port );
		$cl->SetConnectTimeout( 1 );
		$cl->SetWeights( array( 100, 1 ) );
		$cl->SetMatchMode( $mode );		
		$cl->SetArrayResult( true );
		$cl->SetFilter( 'status', array('1'));	
		//$cl->SetFilter( 'state', array('0'));	
		$cl->SetGroupBy("level_1_catid", SPH_GROUPBY_ATTR,"@count DESC" );
				
		$res = $cl->Query( $q, $index );
		$arr = array();
		if($res && isset($res["matches"])){
			if( is_array($res["matches"]) ){
				foreach( $res["matches"] as $results ){	
					$arr[] = $results["attrs"];	
				}							
			}					
		}	
		
		return $arr;
	}
}
?>